package org.jeecg.modules.demo.ddyht.controller;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.ddyht.entity.*;
import org.jeecg.modules.demo.ddyht.service.IDdygInventoryService;
import org.jeecg.modules.demo.ddyht.service.IDdygPiciService;
import org.jeecg.modules.demo.ddyht.service.IJxcCostingService;
import org.jeecg.modules.demo.ddyht.service.IJxcCostingpiciService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.jxcx.po.JxcCustom;
import org.jeecg.modules.demo.jxcx.po.JxcCzrz;
import org.jeecg.modules.demo.jxcx.po.JxcSupplier;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 成本核算批次信息
 * @Author: jeecg-boot
 * @Date:   2025-05-23
 * @Version: V1.0
 */
@Api(tags="成本核算批次信息")
@RestController
@RequestMapping("/ddyht/jxcCostingpici")
@Slf4j
public class JxcCostingpiciController extends JeecgController<JxcCostingpici, IJxcCostingpiciService> {
	@Autowired
	private IJxcCostingpiciService jxcCostingpiciService;
	@Autowired
	private IDdygPiciService ddygPiciService;
	@Autowired
	private IDdygInventoryService ddygInventoryService;
	@Autowired
	private IJxcCostingService jxcCostingService;

	/**
	 * 分页列表查询
	 *
	 * @param jxcCostingpici
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "成本核算批次信息-分页列表查询")
	@ApiOperation(value="成本核算批次信息-分页列表查询", notes="成本核算批次信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<JxcCostingpici>> queryPageList(JxcCostingpici jxcCostingpici,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<JxcCostingpici> queryWrapper = QueryGenerator.initQueryWrapper(jxcCostingpici, req.getParameterMap());
		Page<JxcCostingpici> page = new Page<JxcCostingpici>(pageNo, pageSize);
		IPage<JxcCostingpici> pageList = jxcCostingpiciService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param jxcCostingpici
	 * @return
	 */
	@AutoLog(value = "成本核算批次信息-添加")
	@ApiOperation(value="成本核算批次信息-添加", notes="成本核算批次信息-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody List<JxcCostingpici> jxcCostingpici) {
//		jxcCostingpiciService.save(jxcCostingpici);
		return jxcCostingpiciService.add(jxcCostingpici);
//		return Result.OK("添加成功！");
	}
	 @PostMapping("/queryalltwo")
	 @ResponseBody
	 public Result queryalltwo(@RequestBody JSONObject params) {
		 String companyId = params.getString("companyId");
		 String model = params.getString("model").trim();
//		 String orstate = params.getString("orstate");
		 String orstate = "成本核算";
		 return Result.ok(jxcCostingpiciService.getByalltwo(companyId, model, orstate));
	 }
	 @PostMapping("/unitPriceall")
	 @ResponseBody
	 public Result queryallunitPrice(@RequestBody JSONObject params) {
		 String companyId = params.getString("companyId");
		 String model = params.getString("model");
		 List<DdygPici> getByCompanyId =  ddygPiciService.getByModel(companyId, model,  "1");
		 JSONArray jsonArray = new JSONArray();
		 Set<String> seenUnitPrices = new HashSet<>();
		 for (int i = 0; i < getByCompanyId.size(); i++) {
			 DdygPici ddygPici = getByCompanyId.get(i);
			 String currentUnitPrice = ddygPici.getUnitPrice();
			 if (StringUtils.isNotBlank(ddygPici.getRealnumber())){
				 if (Integer.valueOf(ddygPici.getRealnumber()) > 0) {
					 JSONObject json = new JSONObject();
					 json.put("型号", ddygPici.getModel());
					 json.put("单价", currentUnitPrice);
					 json.put("time", ddygPici.getId().substring(0, 8));
					 if (StringUtils.isNotBlank(ddygPici.getRealnumber())){
						 json.put("数量", ddygPici.getRealnumber());
					 }else {
						 json.put("数量", ddygPici.getNumber());
					 }
					 json.put("onlyid", ddygPici.getOnlyid());
					 jsonArray.add(json);
				 }
			 }else {
				 if (Integer.valueOf(ddygPici.getNumber()) > 0) {
//			 if (!seenUnitPrices.contains(currentUnitPrice)) {
					 JSONObject json = new JSONObject();
					 json.put("型号", ddygPici.getModel());
					 json.put("单价", currentUnitPrice);
					 json.put("time", ddygPici.getId().substring(0, 8));
					 if (StringUtils.isNotBlank(ddygPici.getRealnumber())){
						 json.put("数量", ddygPici.getRealnumber());
					 }else {
						 json.put("数量", ddygPici.getNumber());
					 }
					 json.put("onlyid", ddygPici.getOnlyid());
					 jsonArray.add(json);

//				 seenUnitPrices.add(currentUnitPrice); // 添加到集合中，表示已处理
				 }
			 }
		 }
		 return Result.ok(jsonArray);
	 }
	 @PostMapping(value = "/getBatchDetails")
	 public Result<List<DdygPici>> getBatchDetails(@RequestBody JSONObject jsonObject) {
		 String companyId = jsonObject.getString("companyId");
		 String id = jsonObject.getString("id");
		 String orstate = jsonObject.getString("orstate");
		 List<DdygPici> byall = jxcCostingpiciService.getByall(companyId, id, orstate);
		 return Result.ok(byall);
	 }
	 @PostMapping(value = "/deleteDetails")
	 public Result deleteDetails(@RequestBody JSONObject jsonObject) {
		 LocalDateTime now = LocalDateTime.now();
		 // 定义日期时间格式
		 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
		 String formattedDateTime = now.format(formatter);

		 String companyId = jsonObject.getString("companyId");
		 String id = jsonObject.getString("id");
		 String orstate = jsonObject.getString("orstate");
		 List<JxcCostingpici> byall = jxcCostingpiciService.getByallId(companyId, id);
		 try {
			 for (int i = 0; i < byall.size(); i++) {
				 BigDecimal num = new BigDecimal(byall.get(i).getNumber());
				 DdygPici ddygPici = ddygPiciService.getByOnlyId(byall.get(i).getOnlyid().substring(0,38), companyId);
				 BigDecimal num2 = new BigDecimal(ddygPici.getRealnumber());
				 ddygPici.setRealnumber(num2.add(num)+"");
				 ddygPiciService.updateById(ddygPici);
			 }
		 }catch (Exception e){
			 return Result.error("删除失败"+e);
		 }
		 for (int i = 0; i < byall.size(); i++) {
			 String model = byall.get(i).getModel();
			 BigDecimal num = new BigDecimal(byall.get(i).getNumber());
			 DdygInventory bymodelcompany = ddygInventoryService.getBymodelcompany(model, companyId);
			 if (bymodelcompany != null){
				 BigDecimal number = new BigDecimal(bymodelcompany.getNumber());
				 bymodelcompany.setNumber(number.add(num)+"");
				 ddygInventoryService.updateById(bymodelcompany);
			 }
		 }
		 jxcCostingpiciService.deleteByall(companyId, id, orstate);
		 jxcCostingService.removeById(id);
		 return Result.ok("删除成功");
	 }
	/**
	 *  编辑
	 *
	 * @param jxcCostingpici
	 * @return
	 */
	@AutoLog(value = "成本核算批次信息-编辑")
	@ApiOperation(value="成本核算批次信息-编辑", notes="成本核算批次信息-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody JxcCostingpici jxcCostingpici) {
		jxcCostingpiciService.updateById(jxcCostingpici);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "成本核算批次信息-通过id删除")
	@ApiOperation(value="成本核算批次信息-通过id删除", notes="成本核算批次信息-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		jxcCostingpiciService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "成本核算批次信息-批量删除")
	@ApiOperation(value="成本核算批次信息-批量删除", notes="成本核算批次信息-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.jxcCostingpiciService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "成本核算批次信息-通过id查询")
	@ApiOperation(value="成本核算批次信息-通过id查询", notes="成本核算批次信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<JxcCostingpici> queryById(@RequestParam(name="id",required=true) String id) {
		JxcCostingpici jxcCostingpici = jxcCostingpiciService.getById(id);
		if(jxcCostingpici==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(jxcCostingpici);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param jxcCostingpici
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, JxcCostingpici jxcCostingpici) {
        return super.exportXls(request, jxcCostingpici, JxcCostingpici.class, "成本核算批次信息");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, JxcCostingpici.class);
    }

}
